package com.turing.post.selfwebservice.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.selfwebservice.util.CardHolderUserLink;
import com.turing.post.selfwebservice.util.CardHolderUserLinkDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

/**
 * 注册用户关联卡数据访问实现
 * 
 * @author 李治
 * 
 */
@Stateless(mappedName = "selfwebservice.impl.CardHolderUserLinkDaoImpl")
@Remote
@Local
public class CardHolderUserLinkDaoImpl implements CardHolderUserLinkDao {
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	@SuppressWarnings("unchecked")
	@Override
	public List<CardHolderUserLink> getCardHolderUserLinksByCardHolderUserId(
			BigInteger cardHolderUserId) {
		String sql = "select * from CardHolderUserLink where cardholderuserid= ?1";
		Query query = _em.createNativeQuery(sql, CardHolderUserLink.class)
				.setParameter(1, cardHolderUserId);
		return query.getResultList();
	}

	@Override
	public boolean checkCardLinked(String cardNo) {
		String sql = "select nvl(count(*),0) from CARDHOLDERUSERLINK where CARDNO= ?1";
		Query query = _em.createNativeQuery(sql)
				.setParameter(1, cardNo);
		if (Integer.valueOf(query.getSingleResult().toString()) > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void insertCardHolderUserLink(CardHolderUserLink cardHolderUserLink)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, cardHolderUserLink);
	}

	@Override
	public void deleteCardHolderUserLink(CardHolderUserLink cardHolderUserLink)
			throws PCPSApplicationException {
		String sql = "delete from CARDHOLDERUSERLINK where cardholderuserid=?1 and cardno=?2";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, cardHolderUserLink.getCardHolderUserId());
		query.setParameter(2, cardHolderUserLink.getCardNo());
		try {
			query.executeUpdate();
		} catch (Exception e) {
			throw new PCPSApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_SYS,
					PCPSApplicationException.ERRCODE_CATEGORY_DATABASE,
					"取消持卡用户关联卡失败!");
		}
	}

	@Override
	public CardHolderUserLink getCardHolderUserLinkById(
			CardHolderUserLink cardHolderUserLink) {
		return _em.find(CardHolderUserLink.class, cardHolderUserLink);
	}

}
